<template>
  <div class="app-container">

    <el-row :gutter="5">

      <el-col :sm="24" :md="24" :lg="12" :xl="12" :gutter="5">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>人脸检测区域</span>
            <el-switch
              @change="leftSwitchChange"
              class="algoSwitch"
              v-model="leftCanvas.switch"
              inactive-text="绘制检测区域">
            </el-switch>
            <el-button style="float: right; padding: 3px 0" type="text">分辨率：800*600</el-button>
          </div>
          <div class="text item">
            <canvas id="leftCanvas" :class="{active:leftCanvas.switch}" width="520" height="390" ref="leftCanvas" @mousedown="mousedown($event,'leftCanvas')" @mouseup="mouseup($event,'leftCanvas')" @mousemove="mousemove($event,'leftCanvas')"></canvas>
          </div>
          <br>
          <el-form :inline="true" :model="leftCanvas" class="demo-form-inline">
            <el-form-item label="x">
              <el-input class="width70" disabled v-model="leftCanvas.left" placeholder="x"></el-input>
            </el-form-item>
            <el-form-item label="y">
              <el-input class="width70" disabled v-model="leftCanvas.top" placeholder="y"></el-input>
            </el-form-item>
            <el-form-item label="宽">
              <el-input class="width70" disabled v-model="leftCanvas.width" placeholder="宽"></el-input>
            </el-form-item>
            <el-form-item label="高">
              <el-input class="width70" disabled v-model="leftCanvas.height" placeholder="高"></el-input>
            </el-form-item>
          </el-form>

        </el-card>
      </el-col>

      <el-col :sm="24" :md="24" :lg="12" :xl="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>行人检测区域</span>
            <el-switch
              @change="rightSwitchChange"
              class="algoSwitch"
              v-model="rightCanvas.switch"
              inactive-text="绘制检测区域">
            </el-switch>
            <el-button style="float: right; padding: 3px 0" type="text">分辨率：800*600</el-button>
          </div>
          <div  class="text item rightCanvasView">
            <div class="locationLine line1"></div>
            <div class="locationLine line2"></div>
            <canvas id="rightCanvas" :class="{active:rightCanvas.switch}" width="520" height="390" ref="rightCanvas" @mousedown="mousedown($event,'rightCanvas')" @mouseup="mouseup($event,'rightCanvas')" @mousemove="mousemove($event,'rightCanvas')"></canvas>
          </div>
          <br>
          <el-form :inline="true" :model="rightCanvas" class="demo-form-inline">
            <el-form-item label="x">
              <el-input class="width70" disabled v-model="rightCanvas.left" placeholder="x"></el-input>
            </el-form-item>
            <el-form-item label="y">
              <el-input class="width70" disabled v-model="rightCanvas.top" placeholder="y"></el-input>
            </el-form-item>
            <el-form-item label="宽">
              <el-input class="width70" disabled v-model="rightCanvas.width" placeholder="宽"></el-input>
            </el-form-item>
            <el-form-item label="高">
              <el-input class="width70" disabled v-model="rightCanvas.height" placeholder="高"></el-input>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <el-col :sm="24" :md="24" :lg="24" :xl="24">
        <el-card class="box-card" id="saveView">
          <!--<div slot="header" class="clearfix">-->
          <!--<span>卡片名称</span>-->
          <!--<el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>-->
          <!--</div>-->
          <div class="text item">
            <br>
            <el-form :inline="true" :rules="rules" ref="ruleForm" :model="algparam" class="demo-form-inline">
              <el-form-item label="人脸比对阈值" prop="facethresh">
                <el-input v-model="algparam.facethresh" placeholder="0.01~1"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="setalgparam">保存</el-button>
              </el-form-item>

            </el-form>
            <br>
          </div>
        </el-card>
      </el-col>

    </el-row>

  </div>

</template>

<script>
    export default {
        name: "algorithm",
      data() {
        var checkFacethresh = (rule, value, callback) => {
          var reg=/^[0-9]+([.]{1}[0-9]+){0,1}$/
          if(!reg.test(value)){
            return callback(new Error('请输入正确的数字'));
          }else if (value<0.01||value>1) {
            return callback(new Error('范围在 0.01 ~ 1 之间'));
          }else{
            callback();
          }
          // setTimeout(() => {
          //   if (!Number.isInteger(value)) {
          //     callback(new Error('请输入数字值'));
          //   } else {
          //     if (value < 18) {
          //       callback(new Error('必须年满18岁'));
          //     } else {
          //       callback();
          //     }
          //   }
          // }, 1000);
        }
        return {
          leftCanvas:{
            flag: false,
            switch:false,
            x: 0,
            y: 0,
            left:0,
            top:0,
            width:0,
            height:0
          },
          rightCanvas:{
            flag: false,
            switch:false,
            x: 0,
            y: 0,
            left:0,
            top:0,
            width:0,
            height:0
          },
          leftBase:1.538,
          // rightBase:1.230,
          rightBase:1.538,
          flag: false,
          x: 0,
          y: 0,
          backgroundImage:'http://'+this.BASE.serverIP+':8095/download/right.jpg?getTime='+new Date().getTime(),
          value1: false,
          value2: false,
          algparam:{
            facethresh:0.1
          },
          rules: {
            facethresh: [
              { required: true, message: '请输入人脸比对阈值', trigger: 'blur' },
              { validator: checkFacethresh, trigger: 'blur' }
            ]
          }
        }
      },
      methods:{
        getalgparam:function(){
          var _this=this
          _this.postAjax({
            method:'getalgparam',
            params:{}
          }).then(function (res) {
            console.log(res);
            if(res.result==0){
              var data=res.params,
                leftCanvas=data.facearea.split(','),
                rightCanvas=data.pedarea.split(',')
              _this.algparam.facethresh=data.facethresh==1?1:(data.facethresh).toFixed(2)

              _this.leftCanvas.left=leftCanvas[0]
              _this.leftCanvas.top=leftCanvas[1]
              _this.leftCanvas.width=leftCanvas[2]
              _this.leftCanvas.height=leftCanvas[3]
              _this.mapping({
                targetCanvas:'leftCanvas',
                x:Math.ceil(leftCanvas[0]/_this.leftBase),
                y:Math.ceil(leftCanvas[1]/_this.leftBase),
                width:Math.ceil(leftCanvas[2]/_this.leftBase),
                height:Math.ceil(leftCanvas[3]/_this.leftBase)
              })
              console.log(_this.leftCanvas.left, _this.leftCanvas.top, _this.leftCanvas.width, _this.leftCanvas.height);
              _this.rightCanvas.left=rightCanvas[0]
              _this.rightCanvas.top=rightCanvas[1]
              _this.rightCanvas.width=rightCanvas[2]
              _this.rightCanvas.height=rightCanvas[3]

              _this.mapping({
                targetCanvas:'rightCanvas',
                x:Math.ceil(rightCanvas[0]/_this.rightBase),
                y:Math.ceil(rightCanvas[1]/_this.rightBase),
                width:Math.ceil(rightCanvas[2]/_this.rightBase),
                height:Math.ceil(rightCanvas[3]/_this.rightBase)
              })
              // debugger
              // _this.form.ntpserverip=data.ntpserverip
              // _this.form.ntpserverport=data.ntpserverport
              // _this.form.ntpserverenable=data.enable==1?true:false
            }else{
              _this.tips(res.errorInfo.detail,'error')
            }
          }).catch(function (err) {
            console.log(err);
          }).finally(function (fn) {
            console.log(fn);
          })
        },
        setalgparam:function(){
          var _this=this
          this.$refs['ruleForm'].validate(function (valid) {
            if (valid) {
              _this.postAjax({
                method:'setalgparam',
                params:{
                  pedarea:_this.rightCanvas.left+','+_this.rightCanvas.top+','+_this.rightCanvas.width+','+_this.rightCanvas.height,
                  facearea:_this.leftCanvas.left+','+_this.leftCanvas.top+','+_this.leftCanvas.width+','+_this.leftCanvas.height,
                  facethresh:_this.algparam.facethresh*1
                }
              }).then(function (res) {
                console.log(res);
                if(res.result==0){
                  _this.tips('保存成功','success')
                  // var data=res.params
                  // // debugger
                  // _this.form.ip=data.ip
                  // _this.form.gateway=data.gateway
                  // _this.form.mask=data.mask
                  // _this.form.dns1=data.dns1
                  // _this.form.dns2=data.dns2
                }else {
                  _this.tips(res.errorInfo.detail,'error')
                }
              }).catch(function (err) {
                console.log(err);
              }).finally(function (fn) {
                // _this.loading=false
                console.log(fn);
              })

            } else {
              console.log('error submit!!');
              return false;
            }
          })
        },
        leftSwitchChange:function(status){
          if(status){
            this.leftCanvas.switch=true
          }else{
            this.leftCanvas.switch=false
          }
        },
        rightSwitchChange:function(status){
          if(status){
            this.rightCanvas.switch=true
          }else{
            this.rightCanvas.switch=false
          }
        },
        mousedown:function(e,targetCanvas){
          console.log("鼠标落下");
          if(targetCanvas=='leftCanvas'&&this.leftCanvas.switch){
            this.leftCanvas.flag=true
            this.leftCanvas.x=e.offsetX; // 鼠标落下时的X
            this.leftCanvas.y=e.offsetY; // 鼠标落下时的X
            this.leftCanvas.left=Math.ceil(e.offsetX*this.leftBase)
            this.leftCanvas.top=Math.ceil(e.offsetY*this.leftBase)
          }else if(targetCanvas=='rightCanvas'&&this.rightCanvas.switch){
            this.rightCanvas.flag=true
            this.rightCanvas.x=e.offsetX; // 鼠标落下时的X
            this.rightCanvas.y=e.offsetY; // 鼠标落下时的X
            this.rightCanvas.left=Math.ceil(e.offsetX*this.rightBase)
            this.rightCanvas.top=Math.ceil(e.offsetY*this.rightBase)
          }
        },
        mouseup:function(e,targetCanvas){
          console.log("鼠标抬起");
          if(targetCanvas=='leftCanvas'){
            this.leftCanvas.flag=false
          }else if(targetCanvas=='rightCanvas'){
            this.rightCanvas.flag=false
          }
        },
        mousemove:function(e,targetCanvas){
          console.log("鼠标移动");
          // console.log(targetCanvas);
          this.drawRect(e,targetCanvas);
        },
        mapping:function(params){
          var canvas = this.$refs[params.targetCanvas],
            _this=this,
            ctx = canvas.getContext("2d")
          // 先清除矩形
          ctx.clearRect(0,0,canvas.width,canvas.height);
          ctx.beginPath();

          //设置线条颜色，必须放在绘制之前
          ctx.strokeStyle = 'red';
          // 线宽设置，必须放在绘制之前
          ctx.lineWidth = 1;
          // 绘制矩形
          ctx.strokeRect(params.x,params.y,params.width,params.height);
        },
        drawRect:function(e,targetCanvas){
          console.log(targetCanvas);
          var canvas = this.$refs[targetCanvas],
              _this=this,
              ctx = canvas.getContext("2d"),
              x=0,
              y=0

          if(targetCanvas=='leftCanvas'&&this.leftCanvas.flag){

            console.log(this.leftCanvas.flag,'左侧开关');
            x = this.leftCanvas.x;
              y = this.leftCanvas.y;
            react()
          }else if(targetCanvas=='rightCanvas'&&this.rightCanvas.flag){
              x = this.rightCanvas.x;
              y = this.rightCanvas.y;
            react()
          }

          function react(){
            console.log(ctx);
            // 先清除矩形
            ctx.clearRect(0,0,canvas.width,canvas.height);
            ctx.beginPath();

            //设置线条颜色，必须放在绘制之前
            ctx.strokeStyle = 'red';
            // 线宽设置，必须放在绘制之前
            ctx.lineWidth = 1;
            // 绘制矩形
            ctx.strokeRect(x,y,e.offsetX-x,e.offsetY-y);
            // 宽
            if(targetCanvas=='leftCanvas'){

              console.log(_this);

              _this.leftCanvas.width=Math.ceil((e.offsetX-x)*_this.leftBase)
              _this.leftCanvas.height=Math.ceil((e.offsetY-y)*_this.leftBase)
              console.log('左侧canvas', '宽', _this.leftCanvas.width, '高', _this.leftCanvas.height);
            }else if(targetCanvas=='rightCanvas'){
              _this.rightCanvas.width=Math.ceil((e.offsetX-x)*_this.rightBase)
              _this.rightCanvas.height=Math.ceil((e.offsetY-y)*_this.rightBase)
              console.log('右侧canvas', '宽', _this.rightCanvas.width, '高', _this.rightCanvas.height);
            }
            // console.log(61,e);
            // console.log(62,ctx);
            console.log('宽：', e.offsetX-x, '，高：', e.offsetY-y,'x：'+x+'，y：'+y);
            console.log("绘制图形");
          }


        },
        getImg:function() {
          //获取抓拍图片
          var _this=this
          _this.getAjax({
            params:{
              opt:'grab-jpeg'
            }
          }).then(function (res) {
            console.log(res);
            if(res=="grab fail!"){
              _this.tips(res,'error')
              return
            }

            try{
              var data=res.split('_'),
                leftCanvas=document.getElementById('leftCanvas'),
                rightCanvas=document.getElementById('rightCanvas')
              leftCanvas.style.backgroundImage= 'url("' + 'http://'+_this.BASE.serverIP+':8095/download/'+ data[1]+'?time='+new Date().getTime()+'")'
              rightCanvas.style.backgroundImage= 'url("' + 'http://'+_this.BASE.serverIP+':8095/download/'+ data[1]+'?time='+new Date().getTime()+'")'
              console.log(data);
            }catch (e) {
              _this.tips('获取抓拍图片失败','error')
            }

          }).catch(function (err) {
            console.log(err);
          }).finally(function (fn) {
            console.log(fn);
          })
        }
      },mounted:function () {
        var leftCanvas=document.getElementById('leftCanvas'),
            rightCanvas=document.getElementById('rightCanvas')
            leftCanvas.style.backgroundImage='url("'+ this.backgroundImage+'")'
            rightCanvas.style.backgroundImage= 'url("'+ this.backgroundImage+'")'
        //     this.getImg()
            this.getalgparam()
      }
    }
</script>

<style  scoped>
  .rightCanvasView{
    position: relative;
  }
  .locationLine{
    position: absolute;
    z-index: 10;
    height: 390px;
    border: 1px solid #1F44CD;
  }
  .locationLine.line1{
    left: 98px;
  }
  .locationLine.line2{
    left: 423px;
  }
  .locationLine.line1:after{
    display: block;
    content: '150';
    color: #1F44CD;
    width: 0;
    position: absolute;
    bottom: -20px;
  }
  .locationLine.line2:after{
    display: block;
    content: '650';
    color: #1F44CD;
    width: 0;
    position: absolute;
    bottom: -20px;
  }
  .el-row {
    margin-bottom: 20px;
  /*&:last-child {*/
     /*margin-bottom: 0;*/
   /*}*/
  }
  >>>#saveView .el-form-item{
   margin-bottom: 0px;
}
>>>.el-card__body{
  padding: 10px;
}
>>>.el-switch__label.is-active{
  color:#303133;
}
  #leftCanvas.active,#rightCanvas.active{
  cursor: crosshair;
}
.width70{
  width: 70px;
}
.algoSwitch{
  margin-left: 20px;
}
.el-col {
  border-radius: 4px;
  margin-bottom: 20px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
#leftCanvas,#rightCanvas{
  /*width: 640px;*/
  /*height: 360px;*/
  background: #99a9bf;
  background-size: cover;
}
</style>
